import {ChangeDetectorRef, Component, EventEmitter, Input, OnChanges, OnInit, Output} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, ValidationErrors, Validators} from '@angular/forms';
import {ApiUrl} from '../../../config/api-url';
import {BaseService} from '../../../shared/service/base.service';
import {Observable, Observer} from 'rxjs';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {AgencyModel} from '../../../models/agency-model';
import {Consts} from "../../../config/consts";
import {HttpHeaders} from "@angular/common/http";

@Component({
  selector: 'app-agency-edit',
  templateUrl: './agency-edit.component.html',
  styleUrls: ['./agency-edit.component.less']
})
export class AgencyEditComponent implements OnInit, OnChanges {

  // 模态框显隐
  @Input()
  isVisible = false;
  // 传入当前机构id
  @Input()
  agencyId = 0;
  // 父子互传值
  @Output()
  emit: EventEmitter<any> = new EventEmitter();
  @Input()
  agency;
  // 提交时提交按钮是否加载中
  isOkLoading: any;
  // 提交时是否显示加载中
  isSpinning: boolean;
  // 模态框表单
  formModel: FormGroup;
  // 编辑机构信息：0、添加，1：编辑
  mobileVerify: any;
  // 1、自然人，2、个体户，3、有限公司
  type: any = 3;

  // 当前选中省的省码
  provinceCode: any;
  // 当前选中市的市码
  cityCode: any;
  // 当前选中县区镇的码
  districtCode: any;

  // 省的集合
  provinceList = [];
  // 市的集合
  cityList: any;
  // 区的集合
  districtList: any;

  // 正在编辑的机构对象信息
  agencyModel: AgencyModel;

  // 身份证正面，文件名称，如 324561165461351。已被剪掉后缀（.jpg等等）
  certPhotoA: string;
  // 身份证反面，文件名称，如 324561165461351。已被剪掉后缀（.jpg等等）
  certPhotoB: string;
  // 营业执照号，文件名称，如 324561165461351。已被剪掉后缀（.jpg等等）
  licensePhoto: string;

  // 上传图片读取的身份证号
  certNo: any;
  // 营业执照里的公司名称
  businessName: any;
  selfFeeList: any;

  // 图片上传地址
  uploadUrl = ApiUrl.FileUrl + "/uploadImage";
  accessToken = 'bearer ' + sessionStorage.getItem(Consts.ACCESS_TOKEN);

  // 访问服务器图片地址
  serverFileUrl: any;

  userInfo: any;

  userId: any;
  // 控制输入费率显示隐藏
  @Input()
  agencyInfoDetailVisible = false;
  private updating: boolean = false; // 标志变量

  constructor(private fb: FormBuilder, private baseService: BaseService ,private changeDetectorRef: ChangeDetectorRef) {
    this.buildForm();
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
  }

  ngOnInit(): void {
    console.log("--------ngOnInit--------")
    this.findBackEndUrl();
    this.findAllProvince();

    this.formModel.get('fee').valueChanges.subscribe(value => {
      if (!this.updating && !this.formModel.get('tiktokRate').value && !this.formModel.get('meiTuanRate').value) {
        this.updating = true; // 设置标志为 true
        this.formModel.patchValue({
          tiktokRate: value,
          meiTuanRate: value
        }, { emitEvent: false }); // 不触发事件
        this.updating = false; // 重置标志
      }
    });

    this.formModel.get('tiktokRate').valueChanges.subscribe(value => {
      if (!this.updating && !this.formModel.get('fee').value && !this.formModel.get('meiTuanRate').value) {
        this.updating = true;
        this.formModel.patchValue({
          fee: value,
          meiTuanRate: value
        }, { emitEvent: false });
        this.updating = false;
      }
    });

    this.formModel.get('meiTuanRate').valueChanges.subscribe(value => {
      if (!this.updating && !this.formModel.get('fee').value && !this.formModel.get('tiktokRate').value) {
        this.updating = true;
        this.formModel.patchValue({
          fee: value,
          tiktokRate: value
        }, { emitEvent: false });
        this.updating = false;
      }
    });
  }


  ngOnChanges() {
    if (this.agencyId > 0) {
      this.mobileVerify = 1;
      this.formModel.get('password').clearValidators();
      this.formModel.get('password')!.markAsPristine();
      this.formModel.get('password')!.updateValueAndValidity();
      this.findAgency(this.agencyId);
    } else {
      this.baseService.zorro.clearFormError(this.formModel);
      this.mobileVerify = 0;
      this.agencyId = 0;
      this.formModel.controls['type'].setValue(3);
    }
  }


  findBackEndUrl() {
    this.baseService.get(ApiUrl.Config + '/findBackEndUrl?type=image').subscribe(
      data => {
        if (data.status == 0) {
          if (data.data == null || data.data.url == null) {
            this.baseService.layer.messageError('找不到地址');
            return;
          }
          this.serverFileUrl = data.data.url;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  findAgency(id) {
    this.baseService.get(ApiUrl.AgencyUrl + '/findAgency?agencyId=' + id).subscribe(res => {
      this.userId = res.data.userId;
      this.certPhotoA = res.data.certPhotoA;
      this.certPhotoB = res.data.certPhotoB;
      this.licensePhoto = res.data.licensePhoto;
      this.formModel.reset({
        type: res.data.type,
        agencyName: res.data.agencyName,
        alias: res.data.alias,
        bussAuthNum: res.data.bussAuthNum,
        address: res.data.address,
        idCardNo: res.data.idCardNo,
        province: res.data.province,
        city: res.data.city,
        district: res.data.district,
        fee: parseFloat((res.data.fee * 100).toFixed(3)),
        tiktokRate: parseFloat((res.data.tiktokRate * 100).toFixed(3)),
        meiTuanRate: parseFloat((res.data.meiTuanRate * 100).toFixed(3)),
        name: res.data.name,
        username: res.data.username,
        mobile: res.data.mobile,
        password: res.data.password,
        certPhotoA: res.data.certPhotoA,
        certPhotoB: res.data.certPhotoB,
        licensePhoto: res.data.licensePhoto,
      });
    });
  }


  buildForm() {
    this.formModel = this.fb.group({
      type: [3, [Validators.required]],
      agencyName: [null, [Validators.required]],
      alias: [null, [Validators.required], [this.aliasValidator]],
      bussAuthNum: [null, [Validators.required], [this.principalCertNoValidator]],
      address: [null],
      idCardNo: [null, [Validators.required], [this.principalCertNoPersonValidator]],
      province: [null],
      city: [null],
      district: [null],
      fee: [null, [Validators.required]],
      tiktokRate: [null, [Validators.required]],
      meiTuanRate: [null, [Validators.required]],
      // user: this.fb.group({
      name: [null, [Validators.required]],
      username: [null, [Validators.required], [this.userNameValidator]],
      mobile: [null, [Validators.required], [this.mobileValidator]],
      password: [null, [Validators.required], [this.passwordValidator]],
      certPhotoA: [null],
      certPhotoB: [null],
      licensePhoto: [null],
      // }),
    });
  }

  // 修改或添加合作伙伴
  handleOk() {
    this.isOkLoading = true;
    if (!this.baseService.zorro.validateFormValidate(this.formModel)) {
      this.isOkLoading = false;
      return;
    }


    // 再次检查 费率
    if (this.formModel.value.fee <= 0) {
      this.formModel.get('fee').markAsDirty();
      this.formModel.get('fee').updateValueAndValidity();
      this.baseService.layer.messageError('请正确输入合作伙伴费率！');
      this.isOkLoading = false;
      return;
    }

    if (!this.agencyInfoDetailVisible && !(/^(([1-9])|([0-9]\.\d{1,3}))$/.test(this.formModel.value.fee))) {
      this.baseService.layer.messageError('费率设置最多支持小数点后3位，例如0.555%');
      this.isOkLoading = false;
      return;
    }

    // 再次检查 费率
    if (this.formModel.value.tiktokRate <= 0) {
      this.formModel.get('tiktokRate').markAsDirty();
      this.formModel.get('tiktokRate').updateValueAndValidity();
      this.baseService.layer.messageError('请正确输入抖音核销费率！');
      this.isOkLoading = false;
      return;
    }

    if (!this.agencyInfoDetailVisible && !(/^(([1-9])|([0-9]\.\d{1,3}))$/.test(this.formModel.value.tiktokRate))) {
      this.baseService.layer.messageError('费率设置最多支持小数点后3位，例如0.555%');
      this.isOkLoading = false;
      return;
    }
    // 再次检查 费率
    if (this.formModel.value.meiTuanRate <= 0) {
      this.formModel.get('meiTuanRate').markAsDirty();
      this.formModel.get('meiTuanRate').updateValueAndValidity();
      this.baseService.layer.messageError('请正确输入美团核销费率！');
      this.isOkLoading = false;
      return;
    }

    if (!this.agencyInfoDetailVisible && !(/^(([1-9])|([0-9]\.\d{1,3}))$/.test(this.formModel.value.meiTuanRate))) {
      this.baseService.layer.messageError('费率设置最多支持小数点后3位，例如0.555%');
      this.isOkLoading = false;
      return;
    }

    // 再次检查 在自然人的前提下检查身份证号和上传的身份证号码是否一致
    if (this.certNo != null && this.type == 1) {
      if (this.formModel.get('idCardNo').value != this.certNo) {
        this.baseService.layer.messageError('证件号码与上传身份证不一致，请核对');
        this.isOkLoading = false;
        return;
      }
    }

    // 再次检查 营业执照名称与上传的营业执照上的名称是否一致
    if (this.businessName != null && this.type != 1) {
      if (this.formModel.get('agencyName').value != this.businessName) {
        this.baseService.layer.messageError('营业执照名称与上传的营业执照上的名称不一致,请核对!');
        this.isOkLoading = false;
      }
    }

    if (!this.isOkLoading) {
      return;
    }

    for (const i in this.districtList) {
      if (this.districtList[i].code == this.districtCode) {
        this.districtCode = this.districtList[i].code;
      }
    }

    // 这里赋值

    let param = {
      id : '',
      name : this.formModel.value.agencyName,
      alias : this.formModel.value.alias,
      type : this.formModel.value.type,
      bussAuthNum : this.formModel.value.bussAuthNum,
      licensePhoto : this.formModel.value.licensePhoto,
      fee : this.formModel.value.fee,
      tiktokRate : this.formModel.value.tiktokRate,
      meiTuanRate : this.formModel.value.meiTuanRate,
      user : {
        id : (this.agencyId > 0) ? this.agencyId : "",
        certPhotoA : this.formModel.value.certPhotoA,
        certPhotoB : this.formModel.value.certPhotoB,
        idCardNo : this.formModel.value.idCardNo,
        province : this.formModel.value.province,
        city : this.formModel.value.city,
        district : this.formModel.value.district,
        address : this.formModel.value.address,
        name: this.formModel.value.name,
        username : this.formModel.value.username,
        mobile: this.formModel.value.mobile,
        password : this.formModel.value.password,
      }
    }

    this.isSpinning = true;
    // 如果是添加agencyId=0，修改agencyId肯定大于0

    this.baseService.post(ApiUrl.AgencyUrl, param).subscribe((res) => {
      if (res.status == 0) {
        this.agency = null;
        this.formModel?.reset({});
        this.isVisible = false;
        this.agencyInfoDetailVisible = false;
        this.certNo = null;
        this.businessName = null;
        this.certPhotoA = null;
        this.certPhotoB = null;
        this.licensePhoto = null;
        this.emit.emit(this.isVisible);
        this.emit.emit(this.agencyInfoDetailVisible);
        if (this.agencyId > 0) {
          this.baseService.layer.messageSuccess('修改成功');
        } else {
          this.baseService.layer.messageSuccess('添加成功');
        }
      } else {
        if (this.agencyId > 0) {
          this.baseService.layer.messageError('修改失败：' + res.msg);
        } else {
          this.baseService.layer.messageError('添加失败：' + res.msg);
        }
      }
      this.isOkLoading = false;
      this.isSpinning = false;
    });
  }

  // 取消
  handleCancel() {
    // if (this.agencyId > 0) {
    //   // this.formModel?.reset({});
    // }
    this.agencyId = 0;
    this.userId = 0;
    this.certPhotoA = null;
    this.certPhotoB = null;
    this.licensePhoto = null;
    this.formModel?.reset({});
    this.certNo = null;
    this.businessName = null;
    this.isVisible = false;
    this.emit.emit(this.isVisible);
    this.agencyInfoDetailVisible = false;
    this.emit.emit(this.agencyInfoDetailVisible);
  }

  // 查出所有的省
  findAllProvince() {
    this.baseService.get(ApiUrl.RegionUrl + '/findAllProvince').subscribe(
      data => {
        if (data.status == 0) {
          this.provinceList = data.data;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }


  // 选择省，根据省码找到所有市
  provinceChange(value): void {
    if (value == null) {
      return;
    }
    this.provinceCode = value;
    this.baseService.get(ApiUrl.RegionUrl + '/findAllCityOrDistrict', value)
      .subscribe(data => {
        if (data.status == 0) {
          this.cityList = data.data;
        }
      });
  }

  // 选择市，根据市码找到所有县、区、镇
  cityChange(value: string): void {
    if (value == null) {
      return;
    }
    this.cityCode = value;
    this.baseService.get(ApiUrl.RegionUrl + '/findAllCityOrDistrict', value)
      .subscribe(data => {
        if (data.status == 0) {
          this.districtList = data.data;
        }
      });
  }

  // 选择合作伙伴类型
  changeTypePic() {
    if (this.type != 1) {
      this.formModel.get('idCardNo').clearValidators();
      this.formModel.get('idCardNo')!.markAsPristine();
      this.formModel.get('idCardNo')!.updateValueAndValidity();
      this.formModel.get('bussAuthNum')!.setValidators(Validators.required);
      this.formModel.get('bussAuthNum')!.markAsDirty();
      this.formModel.get('bussAuthNum')!.updateValueAndValidity();
    } else {
      this.formModel.get('bussAuthNum').clearValidators();
      this.formModel.get('bussAuthNum')!.markAsPristine();
      this.formModel.get('bussAuthNum')!.updateValueAndValidity();
      this.formModel.get('idCardNo')!.setValidators(Validators.required);
      this.formModel.get('idCardNo')!.markAsDirty();
      this.formModel.get('idCardNo')!.updateValueAndValidity();
    }
  }

  // 压缩图片不失真
  transformFile = (file: NzUploadFile) => {
    return this.baseService.zorro.imgUpload(file);
  };


  //  上传图片
  handleChange(info: any, name: string): void {
    if (info.file.response?.msg) {
      this.baseService.layer.messageWarning(info.file.response?.msg);
      return;
    }
    switch (info.file.status) {
      case 'uploading':
        break;
      case 'done':
        // tslint:disable-next-line:no-non-null-assertion

        this.getBase64(info.file!.originFileObj!, (img: string) => {
          let value = info.file.response.data.keyRes;
          value = value.substring(0, value.lastIndexOf('.'));
          switch (name) {
            case 'certPhotoA':
              // 赋值身份证号
              this.certNo = info.file.response.data?.certNo;
              this.formModel.get('certPhotoA').setValue(value);
              // 拿到图片纯名称
              this.certPhotoA = value;
              this.changeDetectorRef.detectChanges();
              break;
            case 'certPhotoB':
              // 拿到图片纯名称
              this.certPhotoB = value;
              this.formModel.get('certPhotoB').setValue(value);
              this.changeDetectorRef.detectChanges();
              break;
            case 'licensePhoto':
              this.businessName = info.file.response.data?.businessName;
              this.licensePhoto = value;
              this.formModel.get('licensePhoto').setValue(value);
              this.changeDetectorRef.detectChanges();
              break;
          }
        });
        break;
      case 'error':
        this.baseService.layer.messageError('网络错误!稍后重试!');
        break;
    }
  }


  closeImage(name: string) {
    switch (name) {
      case 'certPhotoA':
        this.certPhotoA = null;
        this.formModel.get('certPhotoA').setValue('');
        break;
      case 'certPhotoB':
        this.certPhotoB = null;
        this.formModel.get('certPhotoB').setValue('');
        break;
      case 'licensePhoto':
        this.licensePhoto = null;
        this.formModel.get('licensePhoto').setValue('');
        break;
    }
  }

  img(event) {
    event.stopPropagation();
  }

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }


  // 验证营业执照
  principalCertNoValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      let reg = /(^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$)|(^\d{15}$)/;
      if (this.type === 1) {
        observer.next(null);
        observer.complete();
      } else {
        if (!reg.test(control.value)) {
          observer.next({principalCertNo: true, error: true});
          observer.complete();
        } else {
          this.baseService.promise((resolve) => {
            this.baseService.get(ApiUrl.AgencyUrl + '/checkBussAuthNum?bussAuthNum=' + control.value + '&agencyId=' + this.agencyId).subscribe(
              data => {
                resolve(data);
              });
          }).then((data: any) => {
            if (data.status == 1) {
              observer.next({error: true, duplicated: true});
            } else {
              observer.next(null);
            }
            observer.complete();
          });
        }
      }
    });


  // 验证简称是否重复
  aliasValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      this.baseService.promise((resolve) => {
        let alias = control.value;
        this.baseService.get(ApiUrl.AgencyUrl + '/checkAbbreviation?alias=' + alias + '&id=' + this.agencyId).subscribe(
          data => {
            resolve(data);
          });
      }).then((data: any) => {
        if (data.status == 1) {
          observer.next({error: true, duplicated: true});
        } else {
          observer.next(null);
        }
        observer.complete();
      });
    });


  /**
   * 身份证验证
   * @param control
   */
  principalCertNoPersonValidator = (control: FormControl) =>
    new Observable((observer1: Observer<ValidationErrors | null>) => {
      let reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
      if (this.type != 1) {
        observer1.next(null);
        observer1.complete();
      } else {
        if (!reg.test(control.value)) {
          observer1.next({principalCertNoPerson: true, error: true});
          observer1.complete();
        } else {
          this.baseService.promise((resolve) => {
            this.baseService.get(ApiUrl.UserUrl + '/checkIdCardNo?idCardNo=' + control.value + '&agencyId=' + this.agencyId).subscribe(
              data => {
                resolve(data);
              });
          }).then((data: any) => {
            if (data.status == 0) {
              observer1.next(null);
            } else {
              observer1.next({duplicated: true, error: true});
            }
            observer1.complete();
          });
        }
      }
    });

  /**  登录账号验证 */
  userNameValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      let reg = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
      let valid = reg.test(control.value);
      if (this.mobileVerify == 1) {
        console.log("是否")
        observer.next(null);
        observer.complete();
      } else if (!valid) {
        observer.next({correct: true, error: true});
        observer.complete();
      } else {
        this.baseService.promise((resolve) => {
          this.baseService.get(ApiUrl.UserUrl + '/checkUserName?username=' + control.value + '&agencyId=' + this.agencyId).subscribe(
            data => {
              resolve(data);
            });
        }).then((data: any) => {
          console.log("是否2")
          console.log(data);
          if (data.status == 1) {
            observer.next({error: true, duplicated: true});
          } else {
            observer.next(null);
          }
          observer.complete();
        });
      }
    });

  /**
   * 手机号验证
   * @param control
   */
  mobileValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      let reg = /^1[0-9]{10}$/;
      let valid = reg.test(control.value);
      if (this.mobileVerify == 1) {
        observer.next(null);
        observer.complete();
      } else if (!valid) {
        observer.next({correct: true, mobile1: true});
        observer.complete();
      } else {
        this.baseService.promise((resolve) => {
          this.baseService.get(ApiUrl.UserUrl + '/checkMobile?mobile=' + control.value).subscribe(
            data => {
              resolve(data);
            });
        }).then((data: any) => {
          if (data.status == 1) {
            observer.next({error: true, duplicated: true});
          } else {
            observer.next(null);
          }
          observer.complete();
        });
      }
    });

  /**
   * 密码验证
   * @param control
   */
  passwordValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      console.log(control.value)
      if (this.mobileVerify == 1) {
        observer.next(null);
        observer.complete();
      } else if (control.value == null ){
        observer.next(null);
        observer.complete();
      }
      else if (control.value.length < 6) {
        observer.next({duplicated: true, error: true});
        observer.complete();
      } else {
        observer.next(null);
        observer.complete();
      }
    });

  handlePreview() {

  }
}
